package com.txsj.scan.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.GlobalGoodsInfoDao;
import com.txsj.scan.Constants;
import com.txsj.scan.R;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.GlobalGoodsInfo;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.LabelBean;
import com.txsj.scan.bean.PreBindBean;
import com.txsj.scan.bean.SimpleBatchBean;
import com.txsj.scan.bean.TagGroupInfo;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.event.Action;
import com.txsj.scan.presenter.LabelPresenter;
import com.txsj.scan.utils.AppDateMgr;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.SDLguiUtils;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.utils.glide.GlideImgManager;
import com.txsj.scan.view.ILabelView;
import com.txsj.scan.widget.TextViewFont;
import com.txsj.scan.widget.TitleBarView;
import com.txsj.scan.widget.dialog.CustomDialog;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import static com.txsj.scan.activity.SelectGoodsListActivity.REQUEST_PERMISSION_CODE;

public class LabelActivity extends BaseActivity<LabelPresenter> implements ILabelView, View
        .OnClickListener {

    public static final int REQUEST_CODE = 0x020;
    public static final int RESULT_GOODS_BATCH_CODE = 0x021;
    public static final int RESULT_BATCH_CODE = 0x022;
    public static final int RESULT_GOODS_CODE = 0x023;

    DecimalFormat decimalFormat = new DecimalFormat("0.00");

    TextViewFont tv_close;
    TextView tv_tag_class, tv_tag, tv_cancel_binding, tv_tag_all, tv_tag_surplus, tv_tag_used,
            tv_scan_code, tv_goods_price, tv_batch_num, tv_batch_addTime, tv_batch_overTime,
            tv_goods_name;
    LinearLayout lin_no_binding, ll_bind_tag_batch;
    ImageView iv_tag_img;
    RelativeLayout rela_binding;

    LabelBean labelBean;//本地标签信息
    GoodsInfo goodsInfo;//选定商品信息
    SimpleBatchBean simpleBatchBean;//商品批次选定信息
    PreBindBean preBindBean;//预绑定标签信息
    long id;//绑定标签需要的id
    long tag_id;//预绑定接口或者查询已经预绑定标签的接口
    TagGroupInfo tagGroupInfo;//已完成与绑定的数据
    EpcInfo epcInfo;//查询标签信息返回的数据

    /**
     * 用来更新本地缓存的变量
     * 一旦点击关闭按钮，通过此变量可进行相应的改变
     *  true :改变扫面标签页的数据
     *  false:所有的都不改变
     */
    boolean isBind = false;//是否绑定完成

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_label);
        initView();
        initData();
    }

    private void initData() {
        if (null == getIntent().getSerializableExtra("data")) return;
        labelBean = (LabelBean) getIntent().getSerializableExtra("data");
        if (null != getIntent().getStringExtra("info")) {
            tagGroupInfo = new Gson().fromJson(getIntent().getStringExtra("info"), TagGroupInfo
                    .class);
            id = tagGroupInfo.getId();
        }

        tv_goods_name.setText(getResources().getString(R.string.qingxuanzecibiaoqian));
        tv_goods_price.setVisibility(View.INVISIBLE);

        analysisStr();
    }

    private void analysisStr() {
        if (TextUtils.isEmpty(labelBean.getStrEpc())) return;
        tv_tag_class.setText(labelBean.getClassId() > 9 ? labelBean.getClassId() + "" : "0" +
                labelBean.getClassId());

        setGroupId(labelBean.getGroupId());

        String epcCode = labelBean.getStrEpc().substring(9, labelBean.getStrEpc().length());
        tag_id = Long.parseLong(epcCode, 16);
        /*
         *判断从上一界面返回的数据中是否存在 id != 0，存在说明已经完成了预绑定可直接进行绑定
         */
        if (id == 0) {
            presenter.preBindLabel(tag_id);
        } else {
            showErrorMsg(getResources().getString(R.string.select_goods_please));
        }
    }

    /**
     * 设置补0够8位的groupId
     */
    private void setGroupId(long tagGroupId) {
        String groupId = tagGroupId + "";
        if (groupId.length() < 8) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 8 - groupId.length(); i++) {
                sb.append("0");
            }
            sb.append(groupId);
            groupId = sb.toString();
        }
        tv_tag.setText(groupId);
    }

    private void initView() {
        mTitle = (TitleBarView) findViewById(R.id.mTitle);
        tv_close = (TextViewFont) findViewById(R.id.tv_close);
        tv_tag_class = (TextView) findViewById(R.id.tv_tag_class);
        tv_tag = (TextView) findViewById(R.id.tv_tag);
        tv_tag_all = (TextView) findViewById(R.id.tv_tag_all);
        tv_tag_used = (TextView) findViewById(R.id.tv_tag_used);
        tv_goods_name = (TextView) findViewById(R.id.tv_goods_name);
        tv_tag_surplus = (TextView) findViewById(R.id.tv_tag_surplus);
        tv_scan_code = (TextView) findViewById(R.id.tv_scan_code);
        tv_batch_num = (TextView) findViewById(R.id.tv_batch_num);
        tv_batch_overTime = (TextView) findViewById(R.id.tv_batch_overTime);
        tv_batch_addTime = (TextView) findViewById(R.id.tv_batch_addTime);
        tv_goods_price = (TextView) findViewById(R.id.tv_goods_price);
        tv_cancel_binding = (TextView) findViewById(R.id.tv_cancel_binding);
        lin_no_binding = (LinearLayout) findViewById(R.id.lin_no_binding);
        ll_bind_tag_batch = (LinearLayout) findViewById(R.id.ll_bind_tag_batch);
        rela_binding = (RelativeLayout) findViewById(R.id.rela_binding);
        iv_tag_img = (ImageView) findViewById(R.id.iv_tag_img);

        tv_close.setOnClickListener(this);
        tv_cancel_binding.setOnClickListener(this);
        lin_no_binding.setOnClickListener(this);
        tv_scan_code.setOnClickListener(this);
        tv_goods_price.setOnClickListener(this);
    }

    @Override
    protected LabelPresenter providePresenter() {
        return new LabelPresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel_binding:
                showDiaBinding();
                break;
            case R.id.lin_no_binding:
            case R.id.iv_tag_img://选择商品
                Intent intent = new Intent(LabelActivity.this, GoodsListActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.tv_close:
            case R.id.tv_scan_code:
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断权限
//                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
//                            PackageManager.PERMISSION_GRANTED) {
//                        toScanCode();
//                    } else {
//                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
//                                .CAMERA}, REQUEST_PERMISSION_CODE);
//                    }
//                } else {
//                    toScanCode();
//                }
                toBack();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && null != data && data.hasExtra("data")) {
            switch (resultCode) {
                case RESULT_GOODS_CODE://选择商品返回
                    String json = data.getStringExtra("data");
                    goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
                    //选完商品后进行批次选择
                    Intent intent = new Intent(LabelActivity.this, SimpleGoodsBatchActivity.class);
                    intent.putExtra("data", json);
                    startActivityForResult(intent, REQUEST_CODE);
                    break;
                case RESULT_GOODS_BATCH_CODE://选完商品选批次返回
                    simpleBatchBean = (SimpleBatchBean) data.getSerializableExtra("data");
                    gotoBindBatch();
                    break;
                case RESULT_BATCH_CODE://扫描标签返回

                    break;

            }
        }
    }

    /**
     * 标签及商品信息返回后进行绑定
     */
    private void gotoBindBatch() {
        if (goodsInfo.getGoods_id() == 0) {
            showErrorMsg(getResources().getString(R.string.reselect_goods));
            return;
        }
        if (id == 0) {
            showErrorMsg(getResources().getString(R.string.reselect_label));
            return;
        }
        if (simpleBatchBean == null) {
            showErrorMsg(getResources().getString(R.string.reselect_batch));
            return;
        }
        presenter.bindGoodsBatch(id, goodsInfo.getGoods_id(), simpleBatchBean.getBatch_id());
    }

    //解绑
    private void showDiaBinding() {
        final CustomDialog dialog = new CustomDialog(this);
        dialog.setTitleStr(getResources().getString(R.string.tip));
        dialog.setContent(getResources().getString(R.string.confirm_unbind));
        dialog.setCancelVisiable();
        dialog.setOkVisiable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUnbindBatch();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 取消绑定
     */
    private void gotoUnbindBatch() {
        presenter.unBindBatch(id);
    }

    @Override
    public void onEmpty() {

    }

    @Override
    public void onError(String msg) {
        hideLoading();
        showErrorMsg(msg);
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onbindSuccess() {
        hideLoading();
        showErrorMsg("绑定成功");
        showData();
        isBind = true;
    }

    @Override
    public void onPrebindSuccess(PreBindBean data) {
        hideLoading();
        preBindBean = data;
        id = preBindBean.getId();
        setGroupId(preBindBean.getTag_group_id());

        /**
         * 将完成预绑定的数据添加到标签组的数据库中，若返回再次进入可直接绑定
         */
        try {
            TagGroupInfo tagGroupInfo = new TagGroupInfo();
            tagGroupInfo.setId(preBindBean.getId());
            tagGroupInfo.setClass_id((int) preBindBean.getTag_class_id());
            tagGroupInfo.setGroup_id((int) preBindBean.getTag_group_id());
            tagGroupInfo.setScene_number(preBindBean.getScene_number());
        }catch (Exception e){
            Trace.e("标签组更新失败，类型转换错误");
        }
    }

    @Override
    public void onPrebindError(String msg) {
        hideLoading();
        showErrorMsg(msg);
        if (msg.equals("标签已被使用")){
           final CustomDialog dialog = new CustomDialog(this);
           dialog.setContent(msg);
           dialog.setSimpleOkVisiable(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   toBack();
                   dialog.dismiss();
              }
           });
           dialog.setCanBackPress(false);
           dialog.show();

        }
    }

    @Override
    public void onGetRFIDSuccess(EpcInfo data) {
        hideLoading();
        epcInfo = data;
        Trace.e("绑定完成后：" + new Gson().toJson(data));

        SimpleDateFormat simpleDateFormat0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            tv_batch_num.setText("批次号："+simpleBatchBean.getBatch_id());
            tv_batch_addTime.setText("生产日期："+simpleDateFormat1.format(simpleDateFormat0.parse(simpleBatchBean.getAdd_time())));
            String expiredDate = simpleDateFormat1.format(simpleDateFormat0.parse(simpleBatchBean.getExpiry_time()));
            tv_batch_overTime.setText("9999-12-31".equals(expiredDate)?"长期有效":"过期日期："+ expiredDate);
            ll_bind_tag_batch.setVisibility(View.VISIBLE);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUnbindSuccess() {
        hideLoading();
        showErrorMsg("解绑成功");
        reSetData();
        isBind = false;
    }

    private void reSetData() {
        goodsInfo = null;
        tv_goods_name.setText(getResources().getString(R.string.qingxuanzecibiaoqian));
        tv_goods_price.setVisibility(View.INVISIBLE);
        rela_binding.setVisibility(View.INVISIBLE);
        lin_no_binding.setVisibility(View.VISIBLE);
        ll_bind_tag_batch.setVisibility(View.INVISIBLE);
        iv_tag_img.setVisibility(View.GONE);
    }

    /**
     * 绑定成功后展示数据
     */
    private void showData() {
        GlideImgManager.getLoadCircleImg(this, goodsInfo.getGoods_img(), iv_tag_img);
        iv_tag_img.setVisibility(View.VISIBLE);
        tv_goods_name.setText(goodsInfo.getGoods_name());
        tv_goods_price.setText("￥" + decimalFormat.format(goodsInfo.getGoods_price()));
        lin_no_binding.setVisibility(View.GONE);
        tv_goods_price.setVisibility(View.VISIBLE);
        rela_binding.setVisibility(View.VISIBLE);
        tv_batch_num.setText(getResources().getText(R.string.batch_number) + "：" +
                simpleBatchBean.getBatch_id());
        tv_batch_addTime.setText(getResources().getText(R.string.batch_add_time)
                + "：" + AppDateMgr.getDateFormat(simpleBatchBean.getAdd_time()));
        if (simpleBatchBean.getExpiry_time().indexOf("9999-12-31") != -1) {
            tv_batch_overTime.setText(getResources().getString(R.string.long_time));
        } else {
            tv_batch_overTime.setText(getResources().getString(R.string.expired_date) + "：" +
                    AppDateMgr.getDateFormat(simpleBatchBean.getExpiry_time()));
        }

        refreshLabelCache();
    }

    /**
     * 绑定成功后刷新数据库缓存
     */
    private void refreshLabelCache() {
        //TODO 刷新本地缓存
        presenter.getRFIDDetail(tag_id);
    }

    @Override
    public void onBarCodeLoadSuccess(GoodsInfo data) {
        hideLoading();
        addToSelectList(data);
    }

    @Override
    public void onQrCodeLoadSuccess(EpcInfo data) {
        hideLoading();
        queryGoods(data);
    }

    /**
     * 查询商品信息
     *
     * @param epcInfo
     */
    private void queryGoods(EpcInfo epcInfo) {
        List<GlobalGoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession()
                .getGlobalGoodsInfoDao().queryBuilder()
                .where(GlobalGoodsInfoDao.Properties.Goods_id.eq(epcInfo.getGoods_id()))
                .list();
        if (null != list && list.size() > 0) {
            String json = new Gson().toJson(list.get(0));
            GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
            goodsInfo.setBrand_id(epcInfo.getBrand_id());

            addToSelectList(goodsInfo);
        } else {
            showErrorMsg("未查到该标签所属商品");
        }
    }

    /**
     * 添加到已选中的商品中
     *
     * @param goodsInfo
     */
    private void addToSelectList(GoodsInfo goodsInfo) {
        if (!PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, "").equals(goodsInfo
                .getBrand_id() + "")) {
            showErrorMsg("暂无此商品，请先使用管理端APP添加");
            return;
        }

        Intent intent = new Intent(LabelActivity.this, SimpleGoodsBatchActivity.class);
        intent.putExtra("data", new Gson().toJson(goodsInfo));
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_F4 == keyCode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
                        PackageManager.PERMISSION_GRANTED) {
                    toScanCode();
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                            .CAMERA}, REQUEST_PERMISSION_CODE);
                }
            } else {
                toScanCode();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void toScanCode() {
        SDLguiUtils.getInstance(this).setListener(new SDLguiUtils.OnScanListener() {
            @Override
            public void onScanSuccess(String data) {
                Trace.e("wcj:扫描回调=========:" + data);
                isQrCodeOrScanCode(data);
            }

            @Override
            public void onScanError(String errorMsg) {
                Trace.e("wcj:扫描失败=========:" + errorMsg);
                showErrorMsg(errorMsg);
            }
        }).doDecode();
    }

    /**
     * 判断是条码还是二维码
     *
     * @param data
     */
    private void isQrCodeOrScanCode(String data) {
        if (TextUtils.isEmpty(data)) return;
        if (data.matches("[0-9]+")) {
            presenter.getBarCodeHttp(data);
        } else {
            String result = data.split("/")[data.split("/").length - 1];
            presenter.getQrCodeHttp(result);
        }
    }

    @Override
    public void onBackPressed() {
        toBack();
    }

    /**
     * 返回
     */
    private void toBack() {
        if (isBind) {
            GreenDaoUtils.getSingleTon().getmDaoSession().getTagGroupInfoDao().deleteByKey(tagGroupInfo.getId());
            GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().insertOrReplaceInTx(epcInfo);
            //更新未绑定标签页面的数据
            EventBus.getDefault().post(new Action(Constants.up_remove_data, labelBean));
        }
        finish();
    }
}
